package com.neulogistics.contrib.usercenter.api.application.command.handler;

import com.blackto.lib.mediat.unicast.IRequestHandler;
import com.neulogistics.contrib.usercenter.api.application.command.LoginCommand;
import com.neulogistics.contrib.usercenter.api.application.viewmodel.LoginUserViewModel;
import com.neulogistics.contrib.usercenter.domain.model.aggregate.User;
import com.neulogistics.contrib.usercenter.domain.repository.IUserRepository;
import com.neulogistics.infrastructure.cache.idservice.RedisIdUtil;
import com.neulogistics.infrastructure.common.serviceresult.BaseResponse;
import com.neulogistics.infrastructure.common.serviceresult.ErrorCode;
import com.neulogistics.infrastructure.common.serviceresult.ResultUtils;
import com.neulogistics.infrastructure.common.token.JwtTokenUtil;
import com.neulogistics.infrastructure.common.token.LoginUser;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class LoginCommandHandler implements IRequestHandler<LoginCommand, BaseResponse<LoginUserViewModel>> {
    @Resource
    private IUserRepository userRepository;

    @Resource
    RedisIdUtil redisIdUtil;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public BaseResponse<LoginUserViewModel> handle(LoginCommand command) {
        User user = userRepository.findByUsername(command.username);
        if(user == null){
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "用户名或密码错误");
        }
        // 校验密码
        if(!user.getPassword().equals(command.password)){
            return ResultUtils.error(ErrorCode.NO_AUTH_ERROR, "用户名或密码错误");
        }

        // 生成token
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getUsername(), user.getUserRole().id);
        String accessToken = JwtTokenUtil.generateAccessToken(loginUser);
        String refreshToken = redisIdUtil.generateRefreshToken(JwtTokenUtil.REFRESH_TOKEN_ICR_KEY_PREFIX);

        // 构造结果
        LoginUserViewModel loginUserViewModel = new LoginUserViewModel();
        BeanUtils.copyProperties(user, loginUserViewModel);
        loginUserViewModel.setAccessToken(accessToken);
        loginUserViewModel.setRefreshToken(refreshToken);
        loginUserViewModel.setUserRole(user.getUserRole().id);

        // 写入缓存
        String refreshTokenKey = JwtTokenUtil.getRefreshTokenKey(user.getUserId());
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 7, TimeUnit.DAYS);

        return ResultUtils.success(loginUserViewModel);
    }
}
